import { defineStore } from 'pinia'
import { ref, computed } from 'vue'

import { pphService } from '../services/pphService'

// 🔒 网络状态管理 - 核心离线功能
export const useNetworkStore = defineStore('network', () => {
  // 状态
  const isOnline = ref(navigator.onLine)
  const lastOnlineTime = ref<Date | null>(null)
  const reconnectAttempts = ref(0)
  const maxReconnectAttempts = ref(5)
  const reconnectInterval = ref(3000) // 3秒

  // 计算属性
  const networkStatus = computed(() => {
    if (isOnline.value) {
      return { status: 'online', text: '在线', type: 'success' }
    } else {
      return { status: 'offline', text: '离线', type: 'danger' }
    }
  })

  const canReconnect = computed(() => {
    return reconnectAttempts.value < maxReconnectAttempts.value
  })

  // 方法
  function updateOnlineStatus(online: boolean) {
    const wasOffline = !isOnline.value
    isOnline.value = online
    
    if (online) {
      lastOnlineTime.value = new Date()
      reconnectAttempts.value = 0
      
      if (wasOffline) {
        syncOfflineData()
      }
    } else {
      console.warn('📡 网络连接断开，切换到离线模式')
    }
  }

  function startMonitoring() {
    // 监听浏览器网络事件
    window.addEventListener('online', () => updateOnlineStatus(true))
    window.addEventListener('offline', () => updateOnlineStatus(false))
    
    // 监听自定义网络错误事件
    window.addEventListener('network-error', () => updateOnlineStatus(false))
    
    // 定期检查服务器连接 - 临时禁用以解决断线问题
    // setInterval(async () => {
    //   if (isOnline.value) {
    //     const serverOnline = await checkServerConnection()
    //     if (!serverOnline) {
    //       updateOnlineStatus(false)
    //     }
    //   } else if (canReconnect.value) {
    //     attemptReconnect()
    //   }
    // }, 10000) // 每10秒检查一次
  }

  async function checkServerConnection(): Promise<boolean> {
    try {
      return await pphService.healthCheck()
    } catch {
      return false
    }
  }

  async function attemptReconnect() {
    if (!canReconnect.value) return

    reconnectAttempts.value++

    try {
      const serverOnline = await checkServerConnection()
      if (serverOnline) {
        updateOnlineStatus(true)
        } else {
        setTimeout(() => {
          if (canReconnect.value) {
            attemptReconnect()
          }
        }, reconnectInterval.value)
      }
    } catch (error) {
      console.error('重连失败:', error)
      setTimeout(() => {
        if (canReconnect.value) {
          attemptReconnect()
        }
      }, reconnectInterval.value)
    }
  }

  async function syncOfflineData() {
    try {
      const offlineRecords = getOfflineRecords()
      if (offlineRecords.length > 0) {
        await pphService.syncOfflineRecords(offlineRecords)
        clearOfflineRecords()
        }
    } catch (error) {
      console.error('❌ 离线数据同步失败:', error)
    }
  }

  function saveOfflineRecord(record: any) {
    const offlineRecords = getOfflineRecords()
    offlineRecords.push({
      ...record,
      offline_timestamp: new Date().toISOString(),
      sync_status: 'pending'
    })
    localStorage.setItem('pph_offline_records', JSON.stringify(offlineRecords))
    }

  function getOfflineRecords(): any[] {
    try {
      const data = localStorage.getItem('pph_offline_records')
      return data ? JSON.parse(data) : []
    } catch {
      return []
    }
  }

  function clearOfflineRecords() {
    localStorage.removeItem('pph_offline_records')
  }

  function getOfflineRecordCount(): number {
    return getOfflineRecords().length
  }

  return {
    // 状态
    isOnline,
    lastOnlineTime,
    reconnectAttempts,
    maxReconnectAttempts,
    
    // 计算属性
    networkStatus,
    canReconnect,
    
    // 方法
    startMonitoring,
    updateOnlineStatus,
    checkServerConnection,
    attemptReconnect,
    saveOfflineRecord,
    getOfflineRecords,
    clearOfflineRecords,
    getOfflineRecordCount,
    syncOfflineData
  }
})
